package com.wmlt.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.wmlt.entity.Order;
import com.wmlt.service.AlipayService;
import com.wmlt.service.OrderService;
import com.wmlt.service.UserService;
import com.wmlt.service.impl.AlipayServiceImpl;
import com.wmlt.service.impl.OrderServiceImpl;
import com.wmlt.service.impl.UserServiceImpl;
import com.wmlt.util.GetRequestJsonUtils;
import com.wmlt.util.QRCodeUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


public class AliPayApi extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        resp.setContentType("text/json;charset=utf-8");
        switch (path) {
            case "/aliPayApi/placeAnOrder":
                placeAnOrder(req, resp);
                break;
            case"/aliPayApi/alinotify":
                try {
                    aliNotify(req,resp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            default:
                resp.setStatus(404);
                break;
        }
    }
    public Order order=new Order();
    /**
     * @description: 下单返回二维码
     * @param:
     * @return:
     * @author liyuxiang
     * @date: 2021/4/13 8:56 下午
     */
    private void placeAnOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收订单信息并创建二维码
        response.setContentType("text/json;charset=utf-8");
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(response, request);
        order.setOrderId(jsonObject.getString("orderId"));
        order.setOrderName(jsonObject.getString("orderName"));
        order.setUserId(jsonObject.getString("userId"));
        order.setOrderMonry(jsonObject.getString("orderMonry"));
        order.setCb(jsonObject.getString("cb"));
        order.setOrderMessage(jsonObject.getString("orderMessage"));
        try {
            String s = qrCode(order);
            String fileUrl = QRCodeUtil.encode(s, 160);
            response.getWriter().println(fileUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 支付宝应用设置本地公钥后生成对应的支付宝公钥（非本地生成的公钥）
     */
    private static String alipayPublicKey = "";
    ;

    private AlipayService alipayService=new AlipayServiceImpl();

    /**
     * 生成支付宝二维码
     */
    public String qrCode(Order order) throws Exception {
        return alipayService.newAliOrder(order);
    }

    /**支付宝回调接口*/
    /**
     * 不返回success，支付宝会在25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h）才会结束通知发送。
     */
    public void aliNotify(HttpServletRequest request,HttpServletResponse response) throws Exception {
        try {
            System.out.println("进入支付宝回调地址");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            System.out.println(("支付宝验签参数："+ JSON.toJSONString(requestParams)));
            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, "UTF-8", "RSA2");
            if (flag) {
                alipayService.aliNotify(params);
                System.out.println("支付宝通知更改状态成功!");
//                AliPayWebSocket aliPayWebSocket = new AliPayWebSocket();
//                aliPayWebSocket.sendMessage("支付成功");
                //存入db
                //创建订单
                OrderService orderService = new OrderServiceImpl();
                orderService.inserOrder(order);

                //增加cb
                UserService userService=new UserServiceImpl();
                userService.addUserCb(order.getUserId(),Integer.parseInt(order.getCb()));

            }
        } catch (Throwable e) {
            System.out.println("exception: "+e);
        }
    }


}


